package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

        @Autowired
        private OrderFeignClient orderFeignClient;

        @Autowired
        private AccountFeignClient accountFeignClient;

        @Autowired
        private PaymentInfoMapper paymentInfoMapper;



    /**
     * 保存付款记录
     * @param paymentType
     * @param orderNo
     * @return
     */

    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //根据根据订单号查询付款记录
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        //执行查询
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        //判断
        if(paymentInfo!=null){
            return paymentInfo;
        }

        //创建实体
        paymentInfo =new PaymentInfo();
        //获取用户id
        Long userId = AuthContextHolder.getUserId();
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setOutTradeNo(orderNo);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);

        //2.2 封装交易内容及金额（远程调用订单服务或者账户服务获取）
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //远程调用订单服务获取订单金额及购买项目（VIP会员，专辑、声音）
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在！");
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
                throw new GuiguException(211, "订单状态错误！");
            }
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //远程调用账户服务获取充值金额
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在！");
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
                throw new GuiguException(211, "充值订单状态错误！");
            }
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值" + rechargeInfo.getRechargeAmount());
        }

        //保存付款记录
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }



    /**
     * 用户付款成功后，修改本地交易记录
     * @param transaction 微信交易对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentInfoSuccess(Transaction transaction) {
        //更新paymentInfo表
        String tradeNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, tradeNo));
        //如果订单已经为支付状态 已经更改了
        if(SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())){
            return;
        }

        //修改本地记录
        //修改交易编号
        paymentInfo.setOutTradeNo(transaction.getOutTradeNo());
        //修改回调时间 和回调内容
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        //修改支付状态
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfoMapper.insert(paymentInfo);


        //远程调用 修改订单状态（如果是订单支付）
        //3.1 判断支付类型：1301-订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
            Result result = orderFeignClient.orderPaySuccess(tradeNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改订单状态异常：" + tradeNo);
            }
        }

        // TODO 远程修改余额  --(点击充值钱包后,调用微信 后的回调 新增余额)
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
            Result result = accountFeignClient.rechargePaySuccess(tradeNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改余额异常：" + tradeNo);
            }
        }

    }
}
